package models

import (
	"errors"
	//"github.com/go-redis/redis/v8"
	"github.com/go-redis/redis"
	"go-demo/core/cache"
	"strconv"
)

func key(id int, role string) string {
	return "gin.www." + role + "." + strconv.Itoa(id) + "token"
}

func GetToken(id int, role string) (string, error) {
	key := key(id, role)
	token, err := cache.RedisClient.Get(key).Result()
	if err != nil {
		if errors.Is(err, redis.Nil) {
			return "", nil
		}
		return "", err
	}
	return token, err
}

func CheckToken(id int, token string, role string) (err error) {
	if id == 0 {
		err = errors.New("id 必须大于0")
		return
	}
	if len(token) == 0 {
		err = errors.New("token不能为空")
		return
	}
	_token, err0 := GetToken(id, role)
	if err0 != nil {
		err = errors.New("token已过期")
		return
	}
	if _token != token {
		err = errors.New("token已过期")
		return
	}
	if _token == token {
		return
	}
	err = errors.New("未知错误")
	return
}
